import os
import sys
import subprocess

# Get the directory where shipping.py is located
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TOOLS_DIR = os.path.join(BASE_DIR, 'tools') # Define tools directory path

def run_script(script_path):
    """Executes a Python script using the same interpreter and checks for errors."""
    if not os.path.exists(script_path):
        print(f"Error: Script not found at {script_path}")
        return False

    print(f"--- Running {os.path.basename(script_path)} ---")
    try:
        # Use sys.executable to ensure the same Python environment is used
        result = subprocess.run([sys.executable, script_path], check=True, capture_output=True, text=True, cwd=BASE_DIR)
        print(result.stdout)
        if result.stderr:
            print("--- Stderr ---")
            print(result.stderr)
            print("--------------")
        print(f"--- Finished {os.path.basename(script_path)} ---")
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error running {os.path.basename(script_path)}:")
        print(f"Return code: {e.returncode}")
        print("--- Stdout ---")
        print(e.stdout)
        print("--- Stderr ---")
        print(e.stderr)
        print("--------------")
        return False
    except Exception as e:
        print(f"An unexpected error occurred while running {os.path.basename(script_path)}: {e}")
        return False

if __name__ == "__main__":
    print("Starting the shipping process...")

    # Define the scripts to run in order, using paths relative to TOOLS_DIR
    scripts_to_run = [
        os.path.join(TOOLS_DIR, 'rename_en.py'),
        os.path.join(TOOLS_DIR, 'rename_zh.py'),
        os.path.join(TOOLS_DIR, 'letsgo_en.py'),
        os.path.join(TOOLS_DIR, 'letsgo_zh.py'),
    ]

    all_success = True
    for script in scripts_to_run:
        if not run_script(script):
            all_success = False
            print(f"!!! Script {os.path.basename(script)} failed. Stopping execution. !!!")
            break # Stop if one script fails

    if all_success:
        print("\nAll scripts executed successfully.")
    else:
        print("\nOne or more scripts failed.")

    print("Shipping process finished.")

